import json
import numpy as np
from utils.getDataFromMysql import *
from utils.expand import *
from typing import List

class AttributeNode:
    def __init__(self, title_name, year, data):
        self.title_name = title_name
        self.year = year
        self.data = data

    @property
    def title_name(self):
        return self.__title_name

    @title_name.setter
    def title_name(self, title_name):
        self.__title_name = title_name

    @property
    def year(self):
        return self.__year

    @year.setter
    def year(self, year):
        self.__year = year

    @property
    def data(self):
        return self.__data

    @data.setter
    def data(self, data):
        self.__data = data

@timecost
def generateLineChart(result_list: List) -> str:
    json_result = {
        "echartX": [],
        "echartNav": [],
        "columns": [],
        "tableData": [],
        "echartDataLine": []
    }

    if not result_list:
        return json.dumps(json_result)

    year_list = [item.year for item in result_list if item.year]
    unique_year_list = np.unique(year_list).tolist()
    json_result["echartX"] = unique_year_list

    title_list = [f"{item.country}_{item.norm}_{item.units}" for item in result_list]
    unique_title_list = np.unique(title_list).tolist()
    json_result["echartNav"] = unique_title_list

    attribute_list = [
        AttributeNode(f"{item.country}_{item.norm}_{item.units}", item.year, item.data_value)
        for item in result_list
    ]

    columns = [{'prop': 'year', 'label': '年份'}]
    unique_titles = {obj.title_name for obj in attribute_list}
    columns.extend({'prop': title, 'label': title} for title in unique_titles)
    json_result["columns"] = columns

    table_data = []
    for year in unique_year_list:
        row = {'year': year}
        for column in columns[1:]:
            result = next((obj for obj in attribute_list if obj.year == year and obj.title_name == column['prop']), None)
            row[column['prop']] = result.data if result else ''
        table_data.append(row)
    json_result['tableData'] = table_data

    echart_data_line = [
        {
            'name': title,
            'type': 'line',
            'data': [obj.data for obj in attribute_list if obj.title_name == title]
        }
        for title in unique_title_list
    ]
    json_result['echartDataLine'] = echart_data_line

    return json.dumps(json_result)

if __name__ == '__main__':
    sql_query = "SELECT year, country, norm, data_value,units FROM weo_data WHERE country = 'Afghanistan' AND  norm = 'NGDP_R'"
    result_list = getDataBySql(sql_query)
    response = generateLineChart(result_list)
    print(response)
